import axios from "axios";
import { useState, useEffect } from "react";
import { notification } from "antd";
function UsePublish(type) {
  const { username } = JSON.parse(localStorage.getItem("token"));
  const [dataSource, setdataSource] = useState([]);
  useEffect(() => {
    axios(
      `/news?author=${username}&publishState=${type}&_expand=category`
    ).then((res) => {
      setdataSource(res.data);
    });
  }, [username]);

  const handlePublish = (item) => {
    setdataSource(dataSource.filter((data) => data.id !== item.id));
    axios
      .patch(`/news/${item.id}`, {
        publishTime: Date.now(),
        publishState: 2,
      })
      .then((res) => {
        notification.open({
          message: "提示",
          description: `操作成功`,
        });
      });
  };
  const handleSunset = (item) => {
    setdataSource(dataSource.filter((data) => data.id !== item.id));
    axios
      .patch(`/news/${item.id}`, {
        publishState: 3,
      })
      .then((res) => {
        notification.open({
          message: "提示",
          description: `操作成功`,
        });
      });
  };
  const handleDelet = (item) => {
    setdataSource(dataSource.filter((data) => data.id !== item.id));
    axios.delete(`/news/${item.id}`).then((res) => {
      notification.open({
        message: "提示",
        description: `操作成功`,
      });
    });
  };
  return { dataSource, handlePublish, handleSunset, handleDelet };
}

export default UsePublish;
